// 初始状态
const state = {
    user: null,
    token: localStorage.getItem('token') || null,
    allUsers: [],
    isLoading: false
}

// getters
const getters = {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user,
    allUsers: state => state.allUsers,
    isLoading: state => state.isLoading
}

// mutations
const mutations = {
    SET_USER(state, user) {
        state.user = user
    },
    SET_TOKEN(state, token) {
        state.token = token
        if (token) {
            localStorage.setItem('token', token)
        } else {
            localStorage.removeItem('token')
        }
    },
    SET_ALL_USERS(state, users) {
        state.allUsers = users
    },
    SET_LOADING(state, isLoading) {
        state.isLoading = isLoading
    },
    LOGOUT(state) {
        state.user = null
        state.token = null
        state.allUsers = []
        localStorage.removeItem('token')
    }
}

// actions
const actions = {
    // 用户注册
    async register({ commit }, registerData) {
        commit('SET_LOADING', true)
        try {
            const response = await this.$authApi.register(registerData)
            if (response.data.success) {
                commit('SET_USER', response.data.data)
                return { success: true, data: response.data.data, message: '注册成功' }
            } else {
                return { success: false, message: response.data.message }
            }
        } catch (error) {
            const message = error.response?.data?.message || '注册失败，请检查网络连接'
            return { success: false, message }
        } finally {
            commit('SET_LOADING', false)
        }
    },

    // 用户登录
    async login({ commit }, loginData) {
        commit('SET_LOADING', true)
        try {
            const response = await this.$authApi.login(loginData)
            if (response.data.success) {
                const { user, token } = response.data.data
                commit('SET_USER', user)
                commit('SET_TOKEN', token)
                return { success: true, data: response.data.data, message: '登录成功' }
            } else {
                return { success: false, message: response.data.message }
            }
        } catch (error) {
            const message = error.response?.data?.message || '登录失败，请检查网络连接'
            return { success: false, message }
        } finally {
            commit('SET_LOADING', false)
        }
    },

    // 获取所有用户
    async fetchAllUsers({ commit }) {
        commit('SET_LOADING', true)
        try {
            const response = await this.$authApi.getAllUsers()
            if (response.data.success) {
                commit('SET_ALL_USERS', response.data.data)
                return { success: true, data: response.data.data }
            } else {
                return { success: false, message: response.data.message }
            }
        } catch (error) {
            const message = error.response?.data?.message || '获取用户列表失败'
            return { success: false, message }
        } finally {
            commit('SET_LOADING', false)
        }
    },

    // 退出登录
    async logout({ commit, state }) {
        try {
            // 调用退出接口
            await this.$authApi.logout(state.token)
        } catch (error) {
            console.error('退出登录时发生错误:', error)
        } finally {
            commit('LOGOUT')
        }
    },

    // 初始化用户状态（页面刷新时调用）
    initializeAuth({ commit }) {
        const token = localStorage.getItem('token')
        if (token) {
            commit('SET_TOKEN', token)
            // 这里可以添加获取当前用户信息的逻辑
        }
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}